package com.raysdata.smartcity.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by yl on 2016/10/20.
 */
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();

        String url = request.getServletPath();
        // 包含尾缀名的或者为登录相关请求的访问放行
        if (url.matches("\\S+\\.\\S+$") ||
                url.matches("\\S*account/(index|login|loginOut|loginSub|casLogin)$") ||// 权限验证部分
                url.matches("\\S*/validateCodeServlet$") ||// 验证码部分
                url.matches("\\S*/(accountApi|loginApi|orderApi|ldapApi|custAccount)\\S*$")) {// api部分
            filterChain.doFilter(request, response);
        } else {
            // 判断session中用户是否为空
            if (null == session.getAttribute("LoginUser")) {
                // 登出系统
                PrintWriter out = response.getWriter();
                out.write("<html>");
                out.write("<script type=\"text/javascript\">");
                out.write("window.open('" + request.getContextPath() + "/account/loginOut','_top');");
                out.write("</script>");
                out.write("</html>");
            } else {
                // 放行
                filterChain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
